class ArrayUtil {
    /**
     * 组合数组到targetArray
     * @param {*} targetArray 
     * @param {*} allArr [array1, array2... arrayn]
     */
    static concatArrays(targetArray, allArr) {
        let allIndex = 0;
        for (let index = 0; index < allArr.length; index++) {
            let arr = allArr[index];
            for (var j = 0; j < arr.length; j++) {
                targetArray[allIndex++] = arr[j];
            }
        }
    }

    /**
     * 用Uint8Array数组创建ArrayBuffer对象
     * 用法: arrayBufferForUint8(Uint8Array1, Uint8Array2... Uint8Arrayn)
     */
    static arrayBufferFromUint8() {
        let allLength = 0;
        for (let index = 0; index < arguments.length; index++) {
            let arr = arguments[index];
            if (arr) {
                allLength += arr.length;
            }
        }

        let arrayBuffer = new ArrayBuffer(allLength);
        let allBytes = new Uint8Array(arrayBuffer, 0);
        this.concatArrays(allBytes, arguments);
        //console.log(allBytes);
        return arrayBuffer;
    }


    static toArrayBuffer(command, bodyObj) {
        //console.log("command", command, "bodyObj", bodyObj);
        let commandByte = Uint8Array.of(command);
        let bodyBytes = null;
        if (bodyObj) {
            bodyBytes = bodyObj.serializeBinary(); // Serializes to a UInt8Array
        }

        let arrayBuffer = null;
        if (bodyBytes) {
            arrayBuffer = this.arrayBufferFromUint8(commandByte, bodyBytes);
        } else {
            arrayBuffer = this.arrayBufferFromUint8(commandByte);
        }

        return arrayBuffer;
    }

    /**
     * 用法：
     * 1、ArrayUtil.remove(array, item, null, 'getId');
     * 2、ArrayUtil.remove(array, item, 'id');
     * 3、ArrayUtil.remove(array, item);
     * @param {*} arr 
     * @param {*} obj 
     * @param {*} propName 
     * @param {*} callMethod 
     */
    static remove(arr, obj, propName, callMethod) {
        for (let i = 0; i < arr.length; i++) {
            let obj1 = arr[i];
            let f = false;
            if (propName) {
                f = (obj1[propName] == obj[propName]);
            } else if (callMethod) {
                f = (obj1[callMethod].call(obj1) == obj[callMethod].call(obj));
            } else {
                f = (obj1 == obj);
            }
            if (f) {
                arr.splice(i, 1);
                return true;
            }
        }
        return false;
    }
}

export default ArrayUtil;